<template>
  <div class="log-table">
    <slot name="search"></slot>
    <div class="table-box">
      <vxe-grid
        border
        row-key
        ref="xTable2"
        class="sortable-tree-demo"
        :scroll-y="{ enabled: false }"
        :columns="tableColumn"
        :data="tableData2"
        :tree-config="{ children: 'queryOutVOS', expandAll: true }"
        height="100%"
        align="center"
        size="medium"
        highlight-hover-row
        resizable
        :header-cell-class-name="headerStyle"
        :row-class-name="rowClass"
        auto-resize>
        <template #default_button="{ row }">
          <el-button type="text" @click="onAddNext(row)">添加下级</el-button>
          <el-button type="text" @click="onAddEdit(row)">编辑</el-button>
          <el-button type="text" @click="onDel(row)">删除</el-button>
        </template>
      </vxe-grid>
    </div>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import { listRecursiveOrgan, updateOrderBy, delOrgan } from '@api/modules/system.js'
import XEUtils from 'xe-utils'
export default {
  name: 'LogTable',
  emits: ['add-account', 'edit-account'],
  props: {
    source: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      tableColumn: [
        {
          field: 'orgName',
          title: '机构名称',
          treeNode: true,
          align: 'left',
          className: 'drag-btn',
          minWidth: '160',
        },
        { field: 'orgAlias', title: '机构简称', minWidth: '120' },
        { field: 'orgType', title: '机构类型', minWidth: '120' },
        { field: 'createTime', title: '创建时间', width: '180' },
        {
          field: 'oper',
          title: '操作',
          width: '180',
          fixed: 'right',
          slots: { default: 'default_button' },
        },
      ],
      tableData2: [],
      tableData: [],
      isZk: false,
    }
  },
  filters: {},
  created() {
    this.initdata()
    this.treeDrop()
  },
  methods: {
    /* 头部样式 */
    headerStyle({ row, column, rowIndex, columnIndex }) {
      return 'headerStyle'
    },
    rowClass({ row, rowIndex }) {
      return 'rowClass'
    },
    delAccount(type, row) {
      // 删除账号的同时也会将关联的机构删除，请谨慎操作
      const userId = localStorage.pskh_userId || JSON.parse(localStorage.PSKH_USERINFO)?.userId
      let delTips = ''
      if (row.id === userId) {
        delTips = '确定删除当前登录账号？删除登录账号后系统会自动退出！'
      } else {
        delTips = '确定删除该账号？'
      }
      this.$confirm(delTips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$emit('del-account', row, userId)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除',
          })
        })
    },
    onDels(row) {
      this.$confirm('确定删除该职位吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$emit('del-account', row)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除',
          })
        })
    },
    /* 拖拽 */
    treeDrop() {
      let draggedItem = null
      let relatedItem = null
      let willInsertAfter1 = null
      let isDrop = false
      this.$nextTick(() => {
        const xTable = this.$refs.xTable2
        this.sortable2 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
          handle: '.drag-btn',
          // 在列表中或列表之间移动项目时的事件
          onMove: ({ dragged, related, willInsertAfter }) => {
            draggedItem = xTable.getRowNode(dragged).item
            relatedItem = xTable.getRowNode(related).item
            willInsertAfter1 = willInsertAfter
            if (draggedItem.pid === relatedItem.id || draggedItem.pid !== relatedItem.pid || draggedItem.pid === '-1') {
              /* 阻止拖拽出该层级 */
              isDrop = false
              return false
            } else {
              isDrop = true
            }
          },
          onEnd: () => {
            if (isDrop) {
              updateOrderBy({
                operate: willInsertAfter1 ? 'after' : 'before',
                operateId: draggedItem.id,
                targetId: relatedItem.id,
                tenantId: localStorage.pskh_tenantId,
              }).then(res => {
                if (res.status === 200) {
                  this.$message.success(res.message || '拖拽成功')
                  this.initdata()
                }
              })
            } else {
              this.$message.error('禁止跨层级拖拽')
              this.initdata()
            }
          },
        })
      })
    },
    /* 初始化数据 */
    initdata() {
      listRecursiveOrgan().then(res => {
        if (res.status === 200) {
          this.tableData = this.getTreeData(res.data)
          this.tableData2 = [...this.tableData]
          this.$nextTick(() => this.$refs.xTable2.setAllTreeExpand(true))
        }
      })
    },
    getTreeData(data) {
      // 循环遍历json数据
      for (let i = 0; i < data.length; i++) {
        if (data[i].queryOutVOS.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].queryOutVOS = undefined
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].queryOutVOS)
        }
      }
      return data
    },
    /* 创建编辑 */
    onAddEdit(data, type) {
      this.editData = { ...data, isAddNext: false }
      this.$emit('edit-account', this.editData)
    },
    /* 添加下级 */
    onAddNext(data) {
      this.editData = { ...data, isAddNext: true }
      this.$emit('add-account', this.editData)
    },
    /* 删除 */
    onDel(data) {
      this.$confirm('是否删除此数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delOrgan(data.id).then(res => {
            if (res.status === 200) {
              this.$message.success(res.message)
              this.initdata()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除',
          })
        })
    },
    onChangeZk() {
      this.isZk = !this.isZk
      if (this.isZk) {
        this.$refs.xTable2.clearTreeExpand()
      } else {
        this.$refs.xTable2.setAllTreeExpand(true)
      }
    },
    searchData(orgName) {
      const filterName = XEUtils.toValueString(orgName).trim().toLowerCase()
      if (filterName) {
        const filterRE = new RegExp(filterName, 'gi')
        const options = { children: 'queryOutVOS' }
        const searchProps = ['orgName', 'orgAlias']
        const rest = XEUtils.searchTree(
          this.tableData,
          item => searchProps.some(key => XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) > -1),
          options
        )
        XEUtils.eachTree(
          rest,
          item => {
            searchProps.forEach(key => {
              item[key] = XEUtils.toValueString(item[key]).replace(filterRE, match => `${match}`)
            })
          },
          options
        )
        this.tableData2 = rest
      } else {
        this.tableData2 = this.tableData
      }
      this.$nextTick(() => this.$refs.xTable2.setAllTreeExpand(true))
    },
  },
}
</script>
<style lang="scss" scoped>
.log-table {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;

  .search-box {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .search-left {
      display: flex;
      align-items: center;
      width: 70%;
      .search-item {
        max-width: 240px;
      }
      .search-item + .search-item {
        margin-left: 20px;
      }
      .search-inp {
        width: 240px;
      }
      .el-icon-search {
        cursor: pointer;
      }
    }
  }

  .table-box {
    flex: 1;
    position: relative;

    .table-con {
      ::v-deep .headerStyle {
        background-color: #f0f4f9;

        .vxe-cell {
          color: #333333;
          font-size: 14px;

          span {
            font-weight: 600;
          }
        }
      }

      ::v-deep .rowClass {
        .vxe-cell {
          color: #666666;
          font-size: 14px;

          p,
          div,
          span {
            font-size: 14px;
          }
        }
      }
    }
  }

  .bg-pagination {
    margin-top: 10px;
  }
}
/deep/.drag-btn {
  cursor: move;
}
</style>
